<template>
  <div class="mask ">
    <!-- 外层的遮罩 -->
    <div class="mask-cover " v-if="indexPopStore.isShowPop"></div>
    <!-- 设置动画 -->
    <transition name="fade">
      <!-- 内容区 -->
      <div class="mask-content" v-if="indexPopStore.isShowPop">
        <!-- 插槽，放置要插入到遮罩里的内容 -->
        <div class="my-confirm" v-if="indexPopStore.isShowPop">
          <div class="wrapper dispaly-col-center">
            <div class="wrapper-box">
              <div class="detail">
                <div class="close">
                  <img class="pointer" @click="indexPopStore.isShowPop = false"
                       src="/src//assets/image/close.png">
                </div>
                <div class="desc dispaly-col-center">
                  <div class="title" v-if="state.type == 2">{{ name }}宗亲网注册</div>
                  <div class="title" v-if="state.type == 1">{{ name }}宗亲网登录</div>
                  <div class="reg-cntent" v-if="state.okRegister">
                    <div class="item">注册信息已提交</div>
                    <div class="item">请等待审核</div>
                  </div>
                  <template v-else>
                    <div class="form" v-if="state.type == 2">
                      <div class="item dispaly-center" v-for="(item, index) in state.regsiterForm"
                           :key="item.name">
                        <input :type="item.type" :maxlength="item.maxlength"
                               :placeholder="item.placeholder" v-model="item.value">
                        <div class="get-code pointer" @click="getCode"
                             v-if="item.name == 'code' && state.show">
                          获取验证码
                        </div>
                        <div class="get-code" v-if="item.name == 'code' && !state.show">
                          {{ state.count }}s后获取
                        </div>
                      </div>
                    </div>
                    <div class="form" v-if="state.type == 1">
                      <div class="item dispaly-center">
                        <input type="text" placeholder="请填入手机号" maxlength="11"
                               v-model="state.loginFormData.phoneNumber">
                      </div>
                      <div class="item dispaly-center">
                        <input type="text" placeholder="请填入验证码" maxlength="11"
                               v-model="state.loginFormData.code">
                        <div class="get-code pointer" @click="getCode" v-if="state.show">
                          获取验证码
                        </div>
                        <div class="get-code" v-if="!state.show">
                          {{ state.count }}s后获取
                        </div>
                      </div>
                    </div>
                  </template>
                  <div class="btn-box dispaly-align-center" v-if="!state.okRegister">
                    <div class="btn pointer" v-for="(item, index) in state.btnData"
                         @click="changeType(item, index)">
                      <img :src="item.icon.select ? item.icon.selectPath : item.icon.path">
                    </div>
                  </div>
                  <div class="bottom-btn-box">
                    <template v-if="!state.okRegister">
                      <div @click="register" v-if="state.type == 2"
                           class="bottom-btn pointer dispaly-align-center">
                        注册查谱平台
                      </div>
                      <div v-if="state.type == 1" class="bottom-btn pointer dispaly-align-center"
                           @click="login">
                        登录
                      </div>
                    </template>
                    <div v-else @click="ok" class="bottom-btn pointer dispaly-align-center">确定
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </transition>
  </div>

</template>
<script setup>
import {reactive} from 'vue'
import {useIndexPopStore} from '@/store/modules/indexPop'
import {debounce} from '@/util/utils'
import {ElMessage} from 'element-plus'
import {postRegister, postLogin} from '@/api/index/index'
import {useRouter} from 'vue-router'
import {getImageUrl} from '@/util/pub-use'

const indexPopStore = useIndexPopStore()
import {getCurrentInstance} from 'vue'

const app = getCurrentInstance()
const name = app.appContext.config.globalProperties.$name

const state = reactive({
  btnData: [
    {
      name: 'login', type: 1, icon: {
        path: getImageUrl('no-login.png'),
        selectPath: getImageUrl('ok-login.png'),
        select: true
      }
    }, {
      name: 'reg', type: 2, icon: {
        path: getImageUrl('no-reg.png'),
        selectPath: getImageUrl('ok-reg.png'),
        select: false
      }
    },

  ],
  // （父亲id编号-父亲名称）
  regsiterForm: [
    {name: 'surnam', placeholder: '请填入姓氏', value: '', type: "text", maxlength: 3},
    {name: 'name', placeholder: '请填入名字', value: '', type: "text", maxlength: 5},
    {name: 'fatherName', placeholder: '请填入父亲姓名', value: '', type: "text", maxlength: 100},
    {name: 'card', placeholder: '请填入身份证号', value: '', type: "text", maxlength: 18},
    {name: 'phoneNumber', placeholder: '请填入手机号码', value: '', type: "text", maxlength: 11},
    {name: 'code', placeholder: '请填入验证码', value: '', type: "text", maxlength: 6},
  ],
  show: true,
  count: '',
  timer: null,
  type: 1,
  loginFormData: {
    phoneNumber: '',
    code: ''
  },
  okRegister: false
})

// 获取验证码
const getCode = debounce(() => {
  ElMessage({
    message: '验证码已发送，请注意查收！',
    type: 'success',
    plain: true
  })
  countdown()
}, 1500)

// 倒计时
const countdown = () => {
  const TIME_COUNT = 3;
  if (!state.timer) {
    state.count = TIME_COUNT;
    state.show = false;
    state.timer = setInterval(() => {
      if (state.count > 0 && state.count <= TIME_COUNT) {
        state.count -= 1;
      } else {
        state.show = true;
        clearInterval(state.timer);
        state.timer = null;
      }
    }, 1000);
  }
}

// 切换类型
const changeType = (item, index) => {
  state.type = item.type
  state.btnData.forEach((item, idx) => item.icon.select = idx === index);
}

// 注册
const register = async () => {
  let formData = {}
  for (let index = 0; index < state.regsiterForm.length; index++) {
    formData[state.regsiterForm[index].name] = state.regsiterForm[index].value
    if (!state.regsiterForm[index].value) {
      ElMessage({
        message: state.regsiterForm[index].placeholder,
        type: 'error',
        plain: true
      })
      return
    }
  }
  const {card, code, fatherName, name, phoneNumber, surnam} = formData
  const submitData = {
    firstName: surnam,
    lastName: name,
    idCard: card,
    phone: phoneNumber,
    code: code,
    fname: fatherName
  }

  const res = await postRegister(submitData)
  if (res.code == 200) {
    ElMessage({
      message: res.msg,
      type: 'success',
      plain: true
    })
    // indexPopStore.isShowPop = false
    state.okRegister = true

  } else {
    ElMessage({
      message: res.msg,
      type: 'error',
      plain: true
    })
  }
}

const ok = () => {
  indexPopStore.isShowPop = false
  state.okRegister = false
}

// 登录
const router = useRouter()
const login = async () => {
  const {phoneNumber, code} = state.loginFormData
  let submitData = {
    phonenumber: phoneNumber,
    code
  }
  if (!phoneNumber) {
    ElMessage({
      message: '请填写手机号',
      type: 'error',
      plain: true
    })
    return
  }
  if (!code) {
    ElMessage({
      message: '请填写验证码',
      type: 'error',
      plain: true
    })
    return
  }


  const res = await postLogin(submitData)

  if (res.code == 200) {
    localStorage.setItem('token', res.data)
    // router.push({
    //     path: '/donation',
    //     query: {
    //         type: 1
    //     }
    // })
    indexPopStore.isShowPop = false
    location.reload()
    ElMessage({
      message: res.msg,
      type: 'success',
      plain: true
    })
  } else {
    ElMessage({
      message: res.msg,
      type: 'error',
      plain: true
    })
  }
}
</script>
<style scoped lang="scss">
.my-confirm {
  transition: all .5s;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 6666;
  background: rgba(0, 0, 0, 0);

  &.fade {
    transition: all 0.4s;
    background: rgba(0, 0, 0, 0.5);
  }

  .wrapper {
    background: url(../../src/assets/image/pop-bg.png) no-repeat;
    background-size: cover;
    width: 702px;
    height: 762px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

    &.fade {
      transition: all 0.4s;
      transform: translate(-50%, -50%);
      opacity: 1;
    }

    .detail {
      padding: 60px 30px;

      .close {
        // text-align: right;
        position: absolute;
        top: 30px;
        right: 30px;

        img {
          width: 25px;
          height: 25px;
        }
      }

      .desc {

        .title {
          color: $primary-color;
          font-family: FZXBSJW--GB1, FZXBSJW--GB1;
          font-weight: normal;
          font-size: 36px;
        }

        .reg-cntent {
          .item {
            color: $primary-color;
            font-family: FZXBSJW--GB1, FZXBSJW--GB1;
            font-weight: normal;
            font-size: 36px;
            text-align: center;
          }
        }

        .btn-box {
          margin-top: 20px;

          .btn:first-child {
            margin-right: 7px;
          }

          .btn:last-child {
            margin-left: 7px;
          }

          .btn {
            img {
              width: 122px;
              height: 32px;
            }
          }
        }

        .bottom-btn-box {
          margin-top: 20px;

          .bottom-btn {
            background: url(../assets/image/btn-bg.jpg) no-repeat;
            background-size: cover;
            width: 420px;
            height: 62px;
            color: #fff;
            font-size: 25px;
          }
        }

        .form {
          margin-top: 20px;

          .item:last-child {
            margin-bottom: 0;
          }

          .item {
            background: url(../assets/image/ipt-bg.png) no-repeat;
            background-size: cover;
            width: 362px;
            height: 56px;
            margin-bottom: 20px;
            position: relative;

            input::placeholder {
              color: $primary-color;
            }

            input {
              color: $primary-color;
              padding-left: 30px;
            }

            .get-code {
              background-color: $primary-color;
              color: #fff;
              padding: 5px;
              border-radius: 3px;
              position: absolute;
              top: 50%;
              right: 0;
              transform: translate(-50%, -50%);
              font-size: 14px;
            }
          }
        }
      }
    }
  }
}

// 最外层，设置position定位
.mask {
  position: relative;
  color: #2e2c2d;
  // font-size: 16px;
}

//遮罩，设置背景层，z-index值要足够大确保能覆盖，高度 宽度设置满 做到全屏遮罩
.mask-cover {
  background: rgba($color: #000000, $alpha: 0.5);
  position: fixed;
  z-index: 1000;
  // 设置top、left、宽高保证全屏遮罩
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
}

//内容层，z-index要大于遮罩层，确保内容在遮罩上显示
.mask-content {
  position: fixed;
  top: 30%;
  height: 70%;
  z-index: 10000;
}

//动画
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>